package org.dtrd.modules.record.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.dtrd.base.BaseController;
import org.dtrd.common.api.vo.Result;
import org.dtrd.common.aspect.annotation.AutoLog;
import org.dtrd.common.util.DateUtils;
import org.dtrd.config.system.SystemState;
import org.dtrd.modules.base.service.BaseCommonService;
import org.dtrd.modules.patient.entity.po.DtrdEntRdPatient;
import org.dtrd.modules.record.entity.bean.SigninSuggestBean;
import org.dtrd.modules.record.entity.po.DtrdEntRdSigninSuggest;
import org.dtrd.modules.record.entity.request.TimePeriodRequest;
import org.dtrd.modules.record.service.IDtrdEntRdSigninSuggestService;
import org.dtrd.modules.suggest.entity.po.DtrdEntRdDoctorSigninSuggestCategory;
import org.dtrd.modules.suggest.service.IDtrdEntRdDoctorSigninSuggestCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.util.Date;
import java.util.Optional;

import static org.dtrd.common.constant.CommonConstant.*;


@Api(tags = "打卡建议")
@RestController
@RequestMapping("/107/01")
public class SigninSuggestController extends BaseController {

    @Resource
    private IDtrdEntRdSigninSuggestService suggestService;
    @Resource
    private IDtrdEntRdDoctorSigninSuggestCategoryService suggestCategoryService;
    @Autowired
    private BaseCommonService baseCommonService;

    @ApiOperation("添加或修改打卡建议")
    @PostMapping("/1070107")
    public Result<?> saveOrUpdateSuggestRecord(@RequestBody SigninSuggestBean suggest) {
        if (isIntParamInvalid(suggest.getPatientId())
                || isIntParamInvalid(suggest.getSigninType())
                || StrUtil.isBlank(suggest.getSuggestContent())) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        boolean result = suggestService.saveOrUpdateSuggestRecord(suggest);
        String logContent = String.format("添加或修改打卡建议，编辑患者id：%d, 编辑时间: %s", suggest.getPatientId(), suggest.getRecordDate());
        baseCommonService.addLog(logContent, OPERATE_TYPE_SAVE_OR_UPDATE);
        return result ? Result.OK() : error(SystemState.ResponseState.STATE_OPERATION_FAILURE);
    }

    @ApiOperation(value = "获取打卡建议内容", notes = "根据id获取")
    @PostMapping("/1070112")
    @AutoLog(value="获取打卡建议内容", operateType = OPERATE_TYPE_QUERY)
    public Result<?> getSuggest(@RequestParam Integer suggestId) {
        if (isIntParamInvalid(suggestId)) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        DtrdEntRdSigninSuggest suggest = suggestService.getById(suggestId);
        SigninSuggestBean suggestInfo = null;
        if (suggest != null) {
            String typeText = Optional.ofNullable(suggest.getSigninType()).map(id -> suggestCategoryService.getById(id)).map(DtrdEntRdDoctorSigninSuggestCategory::getCategoryName).orElse(null);
            suggest.setSigninTypeText(typeText);
            suggestInfo = new SigninSuggestBean().parseFromPO(suggest);
        }
        return suggestInfo == null ? error(SystemState.ResponseState.STATE_OPERATION_FAILURE) : Result.OK(suggestInfo);
    }

    @ApiOperation("查询打卡建议列表")
    @PostMapping("/1070108")
    public Result<?> getSigninSuggestList(@RequestBody TimePeriodRequest request){
        // patientId = 0 表示查询所有patientId的建议
        if (request.getPatientId() == null || request.getPatientId() < 0) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        String startDate = null;
        String endDate = null;
        String[] timePeriod = handleTimePeriod(request);
        if (timePeriod != null) {
            startDate = timePeriod[0];
            endDate = timePeriod[1];
        }
        if (startDate == null || endDate == null) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        endDate = addOneDay(endDate);
        Integer pageNum = getIntParam(request.getPage(), 1);
        Integer pageSize = getPageSize(request.getPageSize(), 10);
        IPage<SigninSuggestBean> page = suggestService.selectSigninSuggestPage(pageNum, pageSize, request.getPatientId(),startDate, endDate);
        String logContent = String.format("查询打卡建议列表，查询患者id：%d", request.getPatientId());
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(page);
    }

    @ApiOperation(value = "查询打卡建议", notes = "小程序, 获取对应类型建议的最新一条")
    @GetMapping("/1070109")
    @AutoLog(value="查询打卡建议", operateType = OPERATE_TYPE_QUERY)
    public Result<?> getSigninSuggest(@RequestParam Integer patientId, @RequestParam Integer type) {
        LambdaQueryWrapper<DtrdEntRdSigninSuggest> queryWrapper = Wrappers.lambdaQuery(DtrdEntRdSigninSuggest.class)
                .eq(DtrdEntRdSigninSuggest::getPatientId, patientId)
                .eq(DtrdEntRdSigninSuggest::getSigninType, type)
                .orderByDesc(DtrdEntRdSigninSuggest::getRecordTime)
                .last("limit 1");
        DtrdEntRdSigninSuggest po = suggestService.getOne(queryWrapper);
        SigninSuggestBean suggestInfo = new SigninSuggestBean();
        if (po != null) {
            String typeText = Optional.ofNullable(po.getSigninType()).map(id -> suggestCategoryService.getById(id)).map(DtrdEntRdDoctorSigninSuggestCategory::getCategoryName).orElse(null);
            po.setSigninTypeText(typeText);
            suggestInfo.parseFromPO(po);
        }
        String logContent = String.format("查询打卡建议列表，查询患者id：%d, 建议类型：%d", patientId, type);
        baseCommonService.addLog(logContent, OPERATE_TYPE_QUERY);
        return Result.OK(suggestInfo);
    }

    @ApiOperation("删除打卡建议")
    @DeleteMapping("/1070111")
    public Result<?> removeSigninSuggest(@RequestParam Integer suggestId) {
        if (isIntParamInvalid(suggestId)) {
            return error(SystemState.ResponseState.STATE_PARAMS_MISSING);
        }
        boolean result = suggestService.removeById(suggestId);
        String logContent = String.format("删除打卡建议，打卡记录id：%d", suggestId);
        baseCommonService.addLog(logContent, OPERATE_TYPE_DELETE);
        return result ? Result.OK() : error(SystemState.ResponseState.STATE_OPERATION_FAILURE);
    }

    private String addOneDay(String date){
        Date newEndDate = null;
        try {
            newEndDate = DateUtils.parseDate(date, DateUtils.date_sdf.get().toPattern());
            newEndDate = DateUtil.offset(newEndDate, DateField.DAY_OF_MONTH, 1);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return DateUtils.formatDate(newEndDate);
    }

}
